package com.example.timer.entity;

import com.example.timer.cron.CronExpression;
import com.example.timer.enums.ScheduleTypeEnum;

import java.util.Date;

/**
 * @author daiguojun
 * @date 2023-04-26 20:33
 * 数据处理实体类
 */
public class JobInfo {

    private ScheduleTypeEnum type;
    private String name;
    private String scheduleConf;
    /**
     * 记录下次执行时间
     */
    private Long triggerTime;


    public ScheduleTypeEnum getType() {
        return type;
    }

    public void setType(ScheduleTypeEnum type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getScheduleConf() {
        return scheduleConf;
    }

    public void setScheduleConf(String scheduleConf) {
        this.scheduleConf = scheduleConf;
    }

    public Long getTriggerTime() {
        return triggerTime;
    }

    public void setTriggerTime(Long triggerTime) {
        this.triggerTime = triggerTime;
    }

    /**
     * 获取当前任务的下次执行时间
     * @param jobInfo
     * @param fromTime
     * @return
     * @throws Exception
     */
    public void freshNextTriggerTime(JobInfo jobInfo, Date fromTime) throws Exception {
        if (ScheduleTypeEnum.CRON == jobInfo.getType()) {
            this.triggerTime =  new CronExpression(jobInfo.getScheduleConf()).getNextValidTimeAfter(fromTime).getTime();
        } else if (ScheduleTypeEnum.FIX_RATE == jobInfo.getType()) {
            this.triggerTime =  new Date(fromTime.getTime() + Integer.parseInt(jobInfo.getScheduleConf())*1000 ).getTime();
        } else {
            this.triggerTime = null;
        }
    }

    @Override
    public String toString() {
        return "JobInfo{" +
                "type=" + type +
                ", name='" + name + '\'' +
                ", scheduleConf='" + scheduleConf + '\'' +
                ", triggerTime='" + triggerTime + '\'' +
                '}';
    }
}
